import React, { useMemo, useRef, useState } from 'react';
import { Input, Tabs, InputNumber, Drawer, Button, Tooltip, Divider, Typography, Steps, Dropdown, Select, Menu, Empty } from 'antd';
import styles from './index.less';
import { Scrollbars } from 'react-custom-scrollbars';
import { PlusOutlined, ArrowRightOutlined, ExclamationCircleFilled, RetweetOutlined, SearchOutlined, FilterOutlined, CloseCircleFilled } from '@ant-design/icons';
import moment from 'moment';
import IconFont from '../IconFont';
import { SketchPicker } from 'react-color';
import { pxConversionMm, mmConversionPx } from "@/utils/transpxmm";
import { useRequest } from 'ahooks';
import { getFetch, postFetch } from '@/utils/doFetch';
import { history } from 'umi';
import PageItem from './pageitem'

const { Paragraph } = Typography;
const { TabPane } = Tabs;

let arr = ["https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202005%2F24%2F20200524064819_uYZr8.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1653049926&t=33d4bcc578fc1fbc25605d5d8a9801dc",
    "https://img1.baidu.com/it/u=3265723691,3851786544&fm=253&fmt=auto&app=138&f=JPEG?w=231&h=499",
    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zmtc.com%2F2020%2F0511%2F20200511035248614.jpg&refer=http%3A%2F%2Fimg.zmtc.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1653049986&t=c75ad09d35e513193e56bb9cc97cc8b8",
    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fp5.itc.cn%2Fq_70%2Fimages03%2F20201008%2Feaa75dec3c9c4f98890cd31f640c25a6.jpeg&refer=http%3A%2F%2Fp5.itc.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1653049986&t=21171e02626a3e1548399ba57715d6df",
    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fd.zdqx.com%2Fios_180727%2F002.jpg&refer=http%3A%2F%2Fd.zdqx.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1653049986&t=f212c35cdab1767ddd517abe8dc0e911",
    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202005%2F24%2F20200524064819_uYZr8.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1653049986&t=7f23efc3c5ce7df7ac53fec1e2b4f513",
    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F8a4c322797b606af971cfaafa12cd0e85460363d12744-AwP5mj_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1653191581&t=6382c2d586e4c3c80eb9b80851275829"
]

function callback(key) {
    console.log(key);
}


function AddTempContent({ width, height, unit, setCur, setiftype, setlayer, tag, refresh }) {
    const [val, setval] = useState();
    const [group, setgroup] = useState();
    const [dirty, setdirty] = useState(false);
    let tabs = useRequest(() => {
        return getFetch({ url: "/api/data_group", params: { is_all: 1 } })
    })
    let createtemp = (value) => {
        if (!value && !val) {
            setdirty("name")
            return
        }
        if (!group) {
            setdirty("group")
            return
        }


        setdirty(false);
        postFetch({
            url: "/api/template", params: {
                name: value ? value : val,
                data_group_id: group,
                size: {
                    width,
                    height,
                    unit,
                    type: tag
                }
            }
        }).then(res => {
            if (res.code == 0) {
                refresh();
                setlayer(true);
                setiftype(s => ({ ...s, visible: false }));
                setCur({
                    id: res?.data?.id
                });
                history.replace({
                    pathname: "/list",
                    query: {
                        id: res?.data?.id,
                        name: val
                    }
                })
            }
        })
    }

    return (
        <div>
            <div className='spread' style={{ marginBottom: 12 }}>
                <span>
                    新建模板
                </span>
                <a style={{ width: 30, color: "#999" }} onClick={() => {
                    setiftype(s => ({ ...s, visible: false }))
                }}>
                    返回
                </a>
            </div>
            <div className="center">
                {
                    dirty == "name" && <ExclamationCircleFilled style={{ color: "red", fontSize: 16, marginRight: 8 }} />
                }
                <Input
                    val={val}
                    onChange={(e) => {
                        setval(e.target.value);
                        if (!e.target.value) {
                            setdirty("name")
                            return
                        }
                        setdirty(false)
                    }}
                    placeholder={"填写模板名称"}
                    bordered={false}
                    style={{ backgroundColor: "#f1f5f3" }}
                    onPressEnter={(e) => {
                        createtemp(e.target.value)
                    }}
                ></Input>
            </div>
            <div className="center">
                <Select
                    placeholder="选择数据组"
                    options={tabs?.data?.data?.dataList && tabs?.data?.data?.dataList.map(it => ({
                        label: it.name,
                        value: it.id
                    }))}
                    bordered={false}
                    showSearch
                    filterOption={(input, option) =>
                        option.label
                            .toLowerCase()
                            .indexOf(input.toLowerCase()) >= 0
                    }
                    style={{ backgroundColor: "#f1f5f3", borderRadius: 8, width: "100%", marginTop: 12 }}
                    val={group}
                    onChange={(vals) => {
                        setgroup(vals);
                        if (!vals) {
                            setdirty("group")
                            return
                        }
                        setdirty(false)
                    }}
                ></Select>
            </div>

            <Button disabled={dirty} style={{ float: "right", marginTop: 12 }} shape="circle" icon={<ArrowRightOutlined />} onClick={() => {
                createtemp()
            }}>
            </Button>
        </div>
    );
}

function TempContent({ setCur, setlayer, setiftype, height, it }) {
    let { data, loading } = useRequest(() => {
        return getFetch({ url: `/api/template/${it.id}`, params: {} })
    })

    return (
        <Scrollbars
            thumbMinSize={10}
            autoHide
            style={{ width: '110%', height: "100%" }}
            hideTracksWhenNotNeeded={true}
        >
            <div style={{ width: 112 }} className={styles.listcontain}>
                <div style={{ paddingBottom: 12 }}>
                    <p className='spread' style={{ alignItems: "flex-start", marginBottom: 8 }}>
                        <span className='oneline' style={{ flex: 1 }}>
                            <Tooltip title={it.name}>
                                {it.name}
                            </Tooltip>
                        </span>
                        <a style={{ width: 30, color: "#999" }} onClick={() => {
                            setiftype(s => ({ ...s, visible: false }))
                        }}>
                            返回
                        </a>
                    </p>
                    <Button disabled={!data?.data?.config || !data?.data?.config?.pages} type="primary" style={{ width: 112 }} onClick={() => {
                        setlayer(true);
                        setiftype(s => ({ ...s, visible: false }));
                        setCur({
                            id: it.id
                        });
                        history.replace({
                            pathname: "/list",
                            query: {
                                id: it.id,
                                name: it.name
                            }
                        })
                    }}>应用这套模板</Button>
                </div>

                {
                    (data?.data?.config && data?.data?.config?.pages?.length > 0) ? data?.data?.config?.pages?.map((it, i) => {
                        return <div
                            key={i}
                            className={styles.items}
                            style={{
                                backgroundImage: it.backgroundColor ? null : `url(${require("@/assets/default.png")})`,
                                marginRight: (i + 1) % 2 == 0 ? 6 : 0,
                                transition: "all 0.4s",
                                height: height,
                                backgroundColor: it.backgroundColor
                            }}
                        >
                            <PageItem page={it}></PageItem>
                            <div className={styles.badge}>
                                {i + 1}
                            </div>
                        </div>
                    }) : <div className="center">
                        暂无数据
                    </div>
                }

            </div>


        </Scrollbars>
    );
}

function Atemp({ setconfig, setlayer, setCur }) {
    let scrollRef = useRef();
    const [size, setsize] = useState({
        width: 1366,
        height: 768
    });
    const [iftype, setiftype] = useState({

    });
    const [filter, setfilter] = useState({

    });


    let tabs = useRequest(() => {
        return getFetch({ url: "/api/data_group", params: { is_all: 1 } })
    })
    const { data, error, loading, refresh } = useRequest(() => getFetch({ url: "/api/template", params: { is_all: 1 } }));
    let alllist = useMemo(() => {
        return data?.data?.dataList ?? []
    }, [data]);

    const menu = (
        <div style={{ width: 120, maxHeight: 600, borderRadius: 8, background: "#FFF", overflow: "hidden" }}>
            {
                tabs?.data?.data?.dataList && tabs?.data?.data?.dataList.map(it => {
                    return <div className="items" onClick={() => {
                        setfilter(it)
                    }}>
                        {it.name}
                    </div>
                })
            }

        </div>
    );


    const publicprops = {
        setconfig,
        setlayer,
        setiftype,
        refresh,
        setCur
    }

    return (
        <div className={styles.container}>
            <div className={styles.searchbar}>
                <Input
                    size="middle"
                    enterButton
                    placeholder={"模板名称"}
                    prefix={<SearchOutlined />}
                ></Input>
                <Dropdown overlay={menu} placement="bottomRight">
                    <Button icon={<FilterOutlined />} style={{ padding: "4px 10px", marginLeft: 6 }}>
                    </Button>
                </Dropdown>
            </div>
            {
                filter.name && <Tooltip title={filter.name} placement="bottomLeft">
                    <span className='titles spread' style={{ width: 136 }}>
                        <b>已选择:</b>
                        <b className='oneline center' style={{ flex: 1, textAlign: "right", justifyContent: "flex-end" }}>
                            {filter.name}
                            <CloseCircleFilled style={{ fontSize: 14, marginLeft: 4 }} onClick={() => {
                                setfilter({})
                            }}></CloseCircleFilled>
                        </b>
                    </span>
                </Tooltip>
            }
            <div className={styles.content} id="template">
                <Drawer
                    maskClosable={true}
                    closable={false}
                    placement="top"
                    destroyOnClose={true}
                    onClose={() => {
                        setiftype(s => ({ ...s, visible: false }))
                    }}
                    getContainer={false}
                    style={{ position: 'absolute' }}
                    {...iftype}
                >
                    {
                        iftype?.render?.()
                    }
                </Drawer>
                <Tabs
                    defaultActiveKey="1"
                    onChange={callback}
                    style={{ height: "100%" }}
                    animated={true}
                >
                    <TabPane tab="手机" key="1">
                        <Scrollbars
                            thumbMinSize={10}
                            autoHide
                            style={{ width: '110%', height: "100%" }}
                            hideTracksWhenNotNeeded={true}
                            ref={scrollRef}
                        >

                            <div className={styles.listcontain}>
                                <div className={`${styles.add} ${styles.item}`} onClick={() => {
                                    let addprops = {
                                        ...publicprops,
                                        width: 1280,
                                        height: 2778,
                                        unit: "px",
                                        tag: "phone",
                                    }

                                    setiftype({
                                        visible: true,
                                        height: 188,
                                        render: () => {
                                            return <AddTempContent {...addprops} />
                                        }
                                    })
                                }}>
                                    <PlusOutlined />
                                    <span>
                                        宽1280*高2778像素
                                    </span>
                                </div>
                                {
                                    alllist.filter(item => {
                                        return (item.data_group_id == filter.id || !filter.id) && (item.size.type == "phone")
                                    }).map((it, i) => {
                                        return <div
                                            key={i}
                                            className={styles.item}
                                            style={{
                                                backgroundImage: `url(${it.poster ?? require("@/assets/default.png")})`,
                                                marginRight: (i + 1) % 2 == 0 ? 6 : 0,
                                                transition: "all 0.4s"
                                            }}
                                            onClick={() => {
                                                setiftype({
                                                    visible: true,
                                                    height: "100%",
                                                    index: i,
                                                    render: () => {
                                                        return <TempContent
                                                            it={it}
                                                            height={(2778 / 1280) * 112}
                                                            {...publicprops}
                                                        />
                                                    }

                                                })

                                            }}
                                        >
                                            <div className={styles.titles}>
                                                {it.name}
                                            </div>
                                            <div className={styles.badge}>
                                                <IconFont type='icon-pages' style={{ color: "#1dac57", fontSize: 30, opacity: 0.5 }}></IconFont>
                                                <b>{parseInt(Math.random() * 10)}</b>
                                            </div>
                                        </div>
                                    })
                                }
                            </div>
                        </Scrollbars>
                    </TabPane>
                    <TabPane tab="电脑" key="2">
                        <Scrollbars
                            thumbMinSize={10}
                            autoHide
                            style={{ width: '110%', height: "100%" }}
                            hideTracksWhenNotNeeded={true}
                            ref={scrollRef}
                        >
                            <div className={styles.listcontain}>
                                <div className={`${styles.add} ${styles.item}`} style={{ height: 73.5 }} onClick={() => {
                                    let addprops = {
                                        ...publicprops,
                                        width: 1920,
                                        height: 1080,
                                        unit: "px",
                                        tag: "cpu",
                                    }
                                    setiftype({
                                        visible: true,
                                        height: 188,
                                        render: () => {
                                            return <AddTempContent {...addprops} />
                                        }
                                    })
                                }}>
                                    <PlusOutlined />
                                    <span>
                                        宽1920*高1080像素
                                    </span>
                                </div>
                                {
                                    alllist.filter(item => {
                                        return (item.data_group_id == filter.id || !filter.id) && (item.size.type == "cpu")
                                    }).map((it, i) => {
                                        return <div
                                            key={i}
                                            className={styles.item}
                                            style={{
                                                backgroundImage: `url(${it.poster ?? require("@/assets/default.png")})`,
                                                marginRight: (i + 1) % 2 == 0 ? 6 : 0,
                                                transition: "all 0.4s",
                                                height: 73.5
                                            }}
                                            onClick={() => {
                                                setiftype({
                                                    visible: true,
                                                    height: "100%",
                                                    index: i,
                                                    render: () => {
                                                        return <TempContent
                                                            it={it}

                                                            height={(1080 / 1920) * 112}
                                                            {...publicprops}

                                                        />
                                                    }

                                                })

                                            }}
                                        >
                                            <div className={styles.titles}>
                                                {it.name}
                                            </div>
                                            <div className={styles.badge}>
                                                <IconFont type='icon-pages' style={{ color: "#1dac57", fontSize: 30, opacity: 0.5 }}></IconFont>
                                                <b>{parseInt(Math.random() * 10)}</b>
                                            </div>
                                        </div>
                                    })
                                }
                            </div>

                        </Scrollbars>
                    </TabPane>
                    <TabPane tab="A4纸" key="3">
                        <Scrollbars
                            thumbMinSize={10}
                            autoHide
                            style={{ width: '110%', height: "100%" }}
                            hideTracksWhenNotNeeded={true}
                            ref={scrollRef}
                        >
                            <div className={styles.listcontain}>
                                <div className={`${styles.add} ${styles.item}`} style={{ height: 177 }} onClick={() => {
                                    let addprops = {
                                        ...publicprops,
                                        width: 210,
                                        height: 297,
                                        unit: "mm",
                                        tag: "A4",
                                    }
                                    setiftype({
                                        visible: true,
                                        height: 188,
                                        render: () => {
                                            return <AddTempContent {...addprops} />
                                        }
                                    })
                                }}>
                                    <PlusOutlined />
                                    <span>
                                        宽210*高297毫米
                                    </span>
                                </div>
                                {
                                    alllist.filter(item => {
                                        return (item.data_group_id == filter.id || !filter.id) && (item.size.type == "A4")
                                    }).map((it, i) => {
                                        return <div
                                            key={i}
                                            className={styles.item}
                                            style={{
                                                backgroundImage: `url(${it.poster ?? require("@/assets/default.png")})`,
                                                marginRight: (i + 1) % 2 == 0 ? 6 : 0,
                                                transition: "all 0.4s",
                                                height: 177
                                            }}
                                            onClick={() => {
                                                setiftype({
                                                    visible: true,
                                                    height: "100%",
                                                    index: i,
                                                    render: () => {
                                                        return <TempContent
                                                            it={it}

                                                            height={(297 / 210) * 112}
                                                            {...publicprops}

                                                        />
                                                    }

                                                })

                                            }}
                                        >
                                            <div className={styles.titles}>
                                                {it.name}
                                            </div>
                                            <div className={styles.badge}>
                                                <IconFont type='icon-pages' style={{ color: "#1dac57", fontSize: 30, opacity: 0.5 }}></IconFont>
                                                <b>{parseInt(Math.random() * 10)}</b>
                                            </div>
                                        </div>
                                    })
                                }

                            </div>

                        </Scrollbars>
                    </TabPane>
                    <TabPane tab="自定义" key="4">
                        <Scrollbars
                            thumbMinSize={10}
                            autoHide
                            style={{ width: '110%', height: "100%" }}
                            hideTracksWhenNotNeeded={true}
                            ref={scrollRef}
                        >
                            <div className={styles.listcontain}>
                                <div style={{ width: 142, display: "flex", alignItems: "center" }}>
                                    <InputNumber style={{ marginRight: 6 }} value={size.width} onChange={(e) => { setsize(s => ({ ...s, width: e })) }} />
                                    <InputNumber style={{ marginRight: 6 }} value={size.height} onChange={(e) => { setsize(s => ({ ...s, height: e })) }} />
                                </div>
                                <div className={styles.adds} onClick={() => {
                                    let addprops = {
                                        ...publicprops,
                                        width: size.width,
                                        height: size.height,
                                        unit: "px",
                                        tag: "other",
                                    }
                                    setiftype({
                                        visible: true,
                                        height: 188,
                                        render: () => {
                                            return <AddTempContent {...addprops} />
                                        }
                                    })
                                }}>
                                    <PlusOutlined />
                                    <span>
                                        宽{size.width}*高{size.height}像素
                                    </span>
                                </div>

                                {
                                    alllist.filter(item => {
                                        return (item.data_group_id == filter.id || !filter.id) && (item.size.type == "other")
                                    }).map((it, i) => {
                                        return <div
                                            key={i}
                                            className={styles.item}
                                            style={{
                                                backgroundImage: `url(${it.poster ?? require("@/assets/default.png")})`,
                                                marginRight: (i) % 2 == 0 ? 6 : 0,
                                                transition: "all 0.4s",
                                                height: 93.5
                                            }}
                                            onClick={() => {
                                                setiftype({
                                                    visible: true,
                                                    height: "100%",
                                                    index: i,
                                                    render: () => {
                                                        return <TempContent
                                                            it={it}
                                                            height={(size.height / size.width) * 112}
                                                            {...publicprops}

                                                        />
                                                    }

                                                })

                                            }}
                                        >
                                            <div className={styles.titles}>
                                                {it.name}
                                            </div>
                                            <div className={styles.badge}>
                                                <IconFont type='icon-pages' style={{ color: "#1dac57", fontSize: 30, opacity: 0.5 }}></IconFont>
                                                <b>{parseInt(Math.random() * 10)}</b>
                                            </div>
                                        </div>
                                    })
                                }


                            </div>

                        </Scrollbars>
                    </TabPane>
                </Tabs>


            </div>
        </div>
    );
}



export default Atemp;